import request from '../utls/require'

let lastKFTime = 0
let lastKFResp: any = null
const KF_TTL_MS = 2000

export const listFootprints = (params: any = {}) => {
  return request({ url: '/xiangsu/carbon/footprints/', method: 'get', params })
}

export const createFootprint = (payload: { text: string, record_date?: string, category?: string }) => {
  return request({ url: '/xiangsu/carbon/footprints/', method: 'post', data: payload })
}

export const getStatistics = (params: { start_date?: string, end_date?: string, group_by?: string }) => {
  return request({ url: '/xiangsu/carbon/statistics/', method: 'get', params })
}

export const getFactors = (params: any = {}) => {
  return request({ url: '/xiangsu/carbon/factors/', method: 'get', params })
}

export const getTrend = (params: { days?: number }) => {
  return request({ url: '/xiangsu/carbon/trend/', method: 'get', params })
}

export const getRecommendations = (params: { horizon_days?: number } = {}) => {
  return request({ url: '/xiangsu/carbon/recommendations/', method: 'get', params })
}

export const getReport = (params: { scope?: string } = {}) => {
  return request({ url: '/xiangsu/carbon/report/', method: 'get', params })
}

export const getKnowledgeFeed = (params: { horizon_days?: number, force?: any } = {}) => {
  const now = Date.now()
  const force = String((params as any)?.force || '').toLowerCase() === 'true'
  if (!force && lastKFResp && now - lastKFTime < KF_TTL_MS) {
    return Promise.resolve(lastKFResp)
  }
  return request({ url: '/xiangsu/carbon/knowledge/', method: 'get', params }).then((resp:any) => {
    lastKFResp = resp
    lastKFTime = Date.now()
    return resp
  })
}

export const getKnowledgeHealth = () => {
  return request({ url: '/xiangsu/carbon/knowledge/health/', method: 'get' })
}

export const getReductionStatistics = (params: { start_date?: string, end_date?: string } = {}) => {
  return request({ url: '/xiangsu/carbon/reduction/statistics/', method: 'get', params })
}
